<template>
  <div class="stock-list-container">
    <!-- 创建商品按钮 -->
    <div class="action-bar">
      <el-button type="primary" @click="createDialogVisible = true">创建商品</el-button>
    </div>

    <!-- 商品库存列表 -->
    <el-table 
      :data="currentPageData" 
      border 
      stripe 
      fit 
      style="width: 100%; margin-top: 20px"
    >
      <el-table-column prop="name" label="商品名称" min-width="120" align="center"/>
      <el-table-column prop="_id" label="id" min-width="150" />
      <el-table-column prop="price" label="价格（元）" width="120" align="center">
        <template #default="scope">¥{{ scope.row.price }}</template>
      </el-table-column>
      <el-table-column prop="category" label="分类" width="150" />

      <el-table-column prop="currentStock" label="当前库存" width="120" align="center" />
      <el-table-column prop="status" label="状态" width="120" align="center">

        <template #default="scope">
          <el-tag :type="scope.row.status === '上架中' ? 'success' : 'danger'">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="120" align="center">
        <template #default="scope">
          <el-button-group class="action-buttons"> 
          <!-- 上架中状态显示下架按钮 -->
          <el-button 
            v-if="scope.row.status === '上架中'" 
            size="small"
            type="danger"
            @click="handleOffline(scope.row._id)"
          >下架</el-button>
<!-- 下架中状态显示上架按钮 -->
          <el-button 
            v-if="scope.row.status === '下架中'" 
            type="success" 
            size="small"
            @click="handleOnline(scope.row._id)"
          >上架</el-button>
          <!--查看详情按钮 -->
          <el-button type="text" size="small" @click="handleViewDetail(scope.row._id)">查看详情</el-button>
        </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="pagination-container">
    <el-pagination
      :current-page="currentPage"
      :page-size="pageSize"
      :total="total"
      layout="prev, pager, next, jumper, ->, total"
      @current-change="handleCurrentChange"
      style="margin-top: 20px;"
    />
  </div>
    <!-- 创建商品对话框 -->
    <el-dialog 
      title="创建新商品" 
      v-model="createDialogVisible"
      width="50%"
    >
      <el-form ref="createFormRef" :model="createForm" :rules="createRules" label-width="100px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="createForm.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input-number 
            v-model="createForm.price" 
            min="0.01" 
            step="0.01" 
            placeholder="请输入商品价格" 
          />
        </el-form-item>
        <el-form-item label="商品分类" prop="category">
          <el-select v-model="createForm.category" placeholder="请选择分类">
            <el-option label="电子产品" value="电子产品" />
            <el-option label="日用品" value="日用品" />
            <el-option label="食品" value="食品" />
          </el-select>
        </el-form-item>
        <el-form-item label="当前库存" prop="currentStock">
          <el-input-number 
            v-model="createForm.currentStock" 
            min="0" 
            placeholder="请输入当前库存" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreateGoods">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { goodsApi } from '@/api/goods'  // 依赖最新的goodsApi接口
import { useRouter } from 'vue-router'
// 商品列表数据（接口返回字段包含status: 上架中/下架中）
const goodsList = ref([])

// 创建商品相关（补充currentStock字段）
const createDialogVisible = ref(false)
const createForm = reactive({
  name: '',
  price: 0,
  category: '',
  currentStock: 0  // 新增库存字段（接口必填）
})
const createRules = {
  name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
  category: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
  currentStock: [{ required: true, message: '请输入当前库存', trigger: 'blur' }]  // 新增校验
}
const createFormRef = ref(null)

//查看详情按钮
const router = useRouter()
const handleViewDetail = (id) => {
  //跳转 到详情页面
  router.push({ path: `/productDetail/${id}` })
}

// 初始化加载商品列表（调用新接口）
onMounted(async () => {
  await fetchGoodsList()
})

// 新增分页状态
const currentPage = ref(1)  // 当前页（初始为1）
const pageSize = ref(10)    // 每页显示10条（固定值）
const total = ref(0)        // 总数据量（等于purchaseOrders长度）

// 计算当前页展示的数据（关键）
const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return goodsList.value.slice(start, end)
})

// 获取商品列表（使用新接口/api/products）
const fetchGoodsList = async () => {
  try {
    const res = await goodsApi.getProductList()  // 替换为新接口
    goodsList.value = res  // 接口直接返回商品数组（无需.data）
    total.value = res.length 
  } catch (err) {
    ElMessage.error(err.response?.data?.message || '获取商品列表失败')
  }
}

// 处理创建商品（调用上架接口）
const handleCreateGoods = async () => {
  await createFormRef.value.validate(async (valid) => {
    if (!valid) return
    try {
      await goodsApi.onlineProduct(createForm)  // 调用上架创建接口
      ElMessage.success('商品创建并上架成功')
      createDialogVisible.value = false
      createFormRef.value.resetFields()
      await fetchGoodsList()  // 刷新列表
    } catch (err) {
      ElMessage.error(err.response?.data?.message || '创建失败（名称重复或字段缺失）')
    }
  })
}

// 处理下架操作（调用下架接口）
const handleOffline = async (id) => {
  try {
    await goodsApi.offlineProduct(id)  // 调用PUT /products/:id/offline
    ElMessage.success('商品已下架')
    await fetchGoodsList()  // 刷新列表
  } catch (err) {
    ElMessage.error(err.response?.data?.message || '下架失败（商品不存在或服务器错误）')
  }
}

// 处理上架操作（假设通过updateProduct接口修改状态）
const handleOnline = async (id) => {
  try {
    // 调用PUT /products/:id 更新状态为"上架中"（需后端支持状态字段修改）
    await goodsApi.reOnlineProduct(id)
    ElMessage.success('商品已重新上架')
    await fetchGoodsList()  // 刷新列表
  } catch (err) {
    ElMessage.error(err.response?.data?.message || '上架失败（商品不存在或服务器错误）')
  }
}
</script>

<style scoped>
.stock-list-container {
  padding: 20px;
}

.action-bar {
  margin-bottom: 20px;
}

.el-table .el-button {
  margin: 0 5px;
}
.pagination-container {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  text-align: center; /* 水平居中 */
  margin: 20px 0; /* 调整上下边距 */
}

/* 可选：调整分页组件内间距 */
.el-pagination {
  padding: 10px 20px; /* 增加内边距使组件更饱满 */
}
/* 同一行左右flex布局 */
.action-buttons{
   display: flex;
   justify-content: space-between;
   align-items: center;

}
</style>